/* eslint-disable no-undef */
const express = require('express');
const cors = require('cors');
const path = require('path');
const helmet = require('helmet');
const config = require('./config/config');
const logger = require('./utils/logger');
const errorHandler = require('./utils/errorHandler');
const { apiLimiter } = require('./utils/rateLimiter');
const createHttpError = require('http-errors');
const app = express();
app.use(helmet()); // 安全头部
app.use(cors()); // 跨域支持
app.use(express.json()); // JSON解析
app.use(express.urlencoded({ extended: true })); // URL编码解析
// 托管 public 目录下的所有静态文件
app.use(express.static(path.join(__dirname, 'dist')));
// 应用级限流
app.use(apiLimiter);
// 路由
app.use('/api/auth', require('./routes/auth.route'));
app.use('/api/chat', require('./routes/chat.route'));
app.use('/api/upload', require('./routes/upload.route'));
app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
// 健康检查端点
app.get('/health', (req, res) => {
  res.status(200).json({ status: 'UP' });
});
// 404处理
app.use((req, res, next) => {
  next(createHttpError(404, 'Not Found'));
});
// 错误处理中间件
app.use(errorHandler);
// 启动服务器
if (require.main === module) {
  const server = app.listen(config.PORT, () => {
    logger.info(`在端口${config.PORT}上运行服务`);
  });

  // 优雅关闭
  process.on('SIGTERM', () => {
    logger.info('SIGTERM已收到。优雅地关机');
    server.close(() => {
      logger.info('Process terminated');
      process.exit(0);
    });
  });
}


